package org.jeecg.modules.api.wlhy.setting;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.DictUtil;
import org.jeecg.modules.wlhy.hyarea.entity.HyArea;
import org.jeecg.modules.wlhy.hyarea.service.IHyAreaService;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 发送小程序订阅消息
 */
public class SendWxMessage {





    public static final String APP_ACCESS_TOKEN_URL= "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ HyConfigUtils.getConfig().getErweimaAppid()+"&secret="+HyConfigUtils.getConfig().getErweimaSecret();

    private static AccessToken at;
    public static String push(String openid, JSONObject hyOrder) {
        RestTemplate restTemplate = new RestTemplate();
        String accessToken = getToken();
        //这里简单起见我们每次都获取最新的access_token（时间开发中，应该在access_token快过期时再重新获取）
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
        //拼接推送的模版
        WxMsgVo wxMsgVo = new WxMsgVo();
        wxMsgVo.setTouser(openid);//用户的openid（要发送给那个用户）
        wxMsgVo.setTemplate_id(HyConfigUtils.getConfig().getTemplateId());//订阅消息模板id
        wxMsgVo.setPage("pages/scan/scanjieguo?msg="+hyOrder.get("id").toString());

        Map<String, TemplateData> m = new HashMap<>(3);

        m.put("thing1", new TemplateData(hyOrder.get("sendAddressName").toString()+"-->"+hyOrder.get("receiveAddressName").toString()));
        m.put("thing2", new TemplateData(hyOrder.get("descriptionOfGoods").toString()));

        String vehicleType="无";
        if(hyOrder.get("vehicleType_dictText")!=null && StringUtils.isNotEmpty(hyOrder.get("remark").toString())){
            vehicleType=hyOrder.get("vehicleType_dictText").toString();
        }
        m.put("thing4", new TemplateData(vehicleType));
        String remark="无";
        if(hyOrder.get("remark")!=null && StringUtils.isNotEmpty(hyOrder.get("remark").toString())){
            remark=hyOrder.get("remark").toString();
        }
        m.put("thing5", new TemplateData(remark));
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String transformDate=simpleDateFormat.format(new Date());
        m.put("time6", new TemplateData(transformDate));
        wxMsgVo.setData(m);
        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMsgVo, String.class);
        return responseEntity.getBody();
    }




    public static String getToken(){
        if (at == null || at.isExpired()){
            getAccessToken();
        }
        return at.getAccessToken();
    }

    /**
     * 获取token
     */
    private static void getAccessToken() {
        //发送请求获取token
        JSONObject token = null;
        try {
            token = AuthUtil.doGetJson(APP_ACCESS_TOKEN_URL);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = token;
        String accessToken = (String) jsonObject.get("access_token");
        Integer expiresIn = (Integer) jsonObject.get("expires_in");
        //创建token对象，并存储
        at = new AccessToken(accessToken,String.valueOf(expiresIn));
    }
}
